package com.sc.nft.consume;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.sc.nft.entity.UserEcologyHatchRecords;
import com.sc.nft.enums.MessageTopic;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.pool.UserPool;
import com.sc.nft.service.EcologySmeltingService;
import com.sc.nft.sup.ErrorCode;
import com.sc.nft.sup.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@RocketMQMessageListener(topic = MessageTopic.ECOLOGY_HATCH_TOPIC+"${spring.profiles.active}",consumerGroup =  MessageTopic.ECOLOGY_HATCH_TOPIC+"${spring.profiles.active}")
@Component
@Slf4j
@RequiredArgsConstructor
public class EcologyHatchConsumer implements RocketMQListener<Long> {

    private final Redisson redisson;
    private final EcologySmeltingService ecologySmeltingService;

    @Override
    public void onMessage(Long userId) {
        log.info("熔炼后-冻结燃料处理 记录id：{},处理开始",userId);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Assert.notNull(userId,"熔炼后-冻结燃料处理 用户id为空");

        RLock lock = redisson.getLock(RedisKeyEnum.ECOLOGY_HATCH_CONSUMER_LOCK.getKey()+userId);
        try{
            boolean res = lock.tryLock(3, 10, TimeUnit.SECONDS);
            if (res) {
                ecologySmeltingService.quotaIncome(userId);
            }else {
                throw new GlobalRunTimeException(ErrorCode.LATER_TRY);
            }
        } catch (InterruptedException e) {
            throw new GlobalRunTimeException(e.getMessage());
        } finally {
            lock.unlock();
        }
        log.info("熔炼后-冻结燃料处理 记录id：{},处理完成",userId);
    }
}
